package com.xfcycle.zebrabikegp.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.bean.BikeInfoResult;
import com.xfcycle.zebrabikegp.bean.QrcodeResult;
import com.xfcycle.zebrabikegp.constant.ActivityChangeConstant;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.SpConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.customView.BottomPopWindow;
import com.xfcycle.zebrabikegp.util.DateFormatUtil;
import com.xfcycle.zebrabikegp.util.EncryptStringUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class MyBikeActivity extends RootActivity {

    private static final String TAG = "MyBikeActivity";

    private ImageView iv_mybike_back;
    private ListView lv_bike_detail;
    private Button btn_add_bike;
    private LinearLayout ll_my_bike_container;

    private Bundle bundle;
    private String uid;
    private String currentConnectBikeId;

    private BikeInfoResult currentBike;

    private BikeInfoResult[] bikeInfoResults;
    private List<BikeInfoResult> bikeDetailList;
    private MyBikeDetailAdapter myBikeDetailAdapter;

    private BottomPopWindow mBottomPopWindow;

    private boolean isChangeBike = false;

    private String currentBindBikeName = "";

    //计算车辆名称前缀
    private String bike_name_prefix = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mybike);

        bundle = getIntent().getExtras();
        uid = bundle.getString("uid");
        currentConnectBikeId = bundle.getString("currentConnectBikeId");

        initView();
        initViewListener();
    }

    @Override
    protected void onResume() {
        super.onResume();

        bikeDetailList.clear();
        getUserBikes();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isChangeBike = false;
    }

    @Override
    public void onBackPressed() {
        customBackEvent();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        iv_mybike_back = (ImageView) findViewById(R.id.iv_mybike_back);
        btn_add_bike = (Button) findViewById(R.id.btn_add_bike);
        lv_bike_detail = (ListView) findViewById(R.id.lv_bike_detail);
        ll_my_bike_container = (LinearLayout) findViewById(R.id.ll_my_bike_container);

        //初始化车辆信息适配器
        bikeDetailList = new ArrayList<>();
        myBikeDetailAdapter = new MyBikeDetailAdapter();
        lv_bike_detail.setAdapter(myBikeDetailAdapter);

        mBottomPopWindow = new BottomPopWindow(this, ll_my_bike_container, new String[]{"Release the bicycle", "Change Name"}) {
            /**
             * 释放车辆
             */
            @Override
            public void lineZeroListener() {
                if (null != currentConnectBikeId && currentConnectBikeId.equals(currentBike.getId())) {
                    Toast.makeText(MyBikeActivity.this.getApplicationContext(), ToastConstant.BIKE_IS_CONNECTING, Toast.LENGTH_LONG).show();
                    return;
                }

                Map<String, String> params = new HashMap<>();
                params.put(WebConstant.SEND_BIKE_INFO_PATH_PARAM_USER_ID, null);
                params.put(WebConstant.SEND_BIKE_INFO_PATH_PARAM_NICKNAME, "");
                new GetJsonFromWebJob(WebConstant.SEND_BIKE_INFO_PATH + currentBike.getId(), WebConstant.PUT, params, REQUEST_SIGN_RELEASE_BIKE_BY_CID, MyBikeActivity.this).start();
            }

            /**
             * 修改车辆昵称
             */
            @Override
            public void lineOneListener() {
                Map<String, String> params = new HashMap<>();
                params.put("cid", currentBike.getId());
                activityChange(BIKE_NICKNAME_CHANGE_ACTIVITY, params, REQUEST_CODE_CHANGE_BIKE_NICKNAME);
            }

            /**
             * 重置车辆
             */
            @Override
            public void lineTwoListener() {
//                Map<String, String> params = new HashMap<>();
//                params.put(WebConstant.SEND_ORDER_TO_BIKE_PATH_PARAM_CMD, "2");
//                new GetJsonFromWebJob(WebConstant.SEND_ORDER_TO_BIKE_PATH_ONE + currentBike.getId() + WebConstant.SEND_ORDER_TO_BIKE_PATH_TWO, WebConstant.PUT, params, REQUEST_SIGN_RESET_BIKE_BY_CID, MyBikeActivity.this).start();
            }

            @Override
            public void lineThreeListener() {
            }

            @Override
            public void lineFourListener() {
            }

            @Override
            public void lineFiveListener() {
            }
        };
    }

    /**
     * 组件监听事件添加
     */
    private void initViewListener() {
        //回退事件监听
        iv_mybike_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                customBackEvent();
            }
        });

        //添加车辆 扫描二维码，添加车辆到用户名下
        btn_add_bike.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(MyBikeActivity.this, CaptureActivity.class), REQUEST_CODE_FIND_BIKE_QRCODE);
            }
        });
    }

    /**
     * 向服务器请求数据
     */
    private void getUserBikes() {
        //查找用户的名下所有自行车
        new GetJsonFromWebJob(WebConstant.GET_USER_BIKE_PATH_ONE + uid + WebConstant.GET_USER_BIKE_PATH_TWO, WebConstant.GET, null, REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO, MyBikeActivity.this).start();
    }

    /**
     * 自定义回退事件
     */
    private void customBackEvent() {
        Bundle backBundle = new Bundle();
        //没做任何事情
        backBundle.putString(ActivityChangeConstant.ACTIVITY_CHANGE_MY_BIKE_ACT_KEY, isChangeBike ? "true" : "false");
        setResult(RESULT_OK, new Intent().putExtras(backBundle));
        finish();
    }
    /***********************************************************************************************/
    /**                             处理从不同途径获得的数据                                         **/
    /***********************************************************************************************/

    /**
     * 处理从网络获得的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        Gson gson = new Gson();
        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        Log.e(TAG, "dealDataFromWeb: ----------- 从服务器获取到的返回结果：" + webResult);

        //判断登陆账号名下是否有车
        if (REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO == webSign) {
            try {
                bikeInfoResults = gson.fromJson(webResult, BikeInfoResult[].class);
            } catch (Exception e) {
                Log.e(TAG, "dealDataFromWeb: ------ 解析json格式字符串失败");
            }
            bikeDetailList.clear();

            if (bikeInfoResults.length <= 0) {
                Log.e(TAG, "dealDataFromWeb: ----------------------- 名下没有任何车辆");
            } else {
                //如果有车，取到车的信息,展示
                for (BikeInfoResult bikeInfoResult : bikeInfoResults) {
                    bikeDetailList.add(bikeInfoResult);
                }
            }
            myBikeDetailAdapter.notifyDataSetChanged();
            return;
        }

        //释放车成功
        if (REQUEST_SIGN_RELEASE_BIKE_BY_CID == webSign && "".equals(webResult)) {
            Log.e(TAG, "dealDataFromWeb: 抛车成功");
            mBottomPopWindow.dismissing();
            getUserBikes();
            isChangeBike = true;
            return;
        }

        //释放车失败
        if (REQUEST_SIGN_RELEASE_BIKE_BY_CID == webSign && !"".equals(webResult)) {
            Log.e(TAG, "dealDataFromWeb: 抛车失败" + webResult);
            Toast.makeText(this.getApplicationContext(), ToastConstant.RELEASE_BILE_FAILURE, Toast.LENGTH_SHORT).show();
            return;
        }

        //重置车成功
        if (REQUEST_SIGN_RESET_BIKE_BY_CID == webSign && "".equals(webResult)) {
            isChangeBike = true;
            return;
        }

        //重置车失败
        if (REQUEST_SIGN_RESET_BIKE_BY_CID == webSign && !"".equals(webResult)) {
            Log.e(TAG, "dealDataFromWeb: 重置车失败" + webResult);
            Toast.makeText(this.getApplicationContext(), ToastConstant.RESET_BILE_FAILURE, Toast.LENGTH_SHORT).show();
            return;
        }

        //依据车出厂名从服务器获取到车的Cid 将该车绑定到用户名下
        if (REQUEST_SIGN_GET_BIKE_BID_BY_BNAME_BIND_USER == webSign) {

            if (webResult.contains("none bike")) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.OBTAIN_BILE_INFO_FAILURE, Toast.LENGTH_SHORT).show();
                return;
            }

            BikeInfoResult bikeInfoResult = gson.fromJson(webResult, BikeInfoResult.class);

            Log.i(TAG, "dealDataFromWeb: --------------- 获取到的车辆信息 " + bikeInfoResult.toString());

            //判断当前车辆已经被绑定
            if (null != bikeInfoResult.getUser_id() && !"".equals(bikeInfoResult.getUser_id())) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.BIKE_HAS_BEEN_BOUND, Toast.LENGTH_SHORT).show();
                return;
            }

            currentBindBikeName = bikeInfoResult.getName();

            //将当前自行车绑定到用户名下
            Map<String, String> params = new HashMap<>();
            params.put(WebConstant.SEND_BIKE_INFO_PATH_PARAM_USER_ID, uid);
            new GetJsonFromWebJob(WebConstant.SEND_BIKE_INFO_PATH + bikeInfoResult.getId(), WebConstant.PUT, params, REQUEST_SIGN_BIND_BIKE_BY_CID, MyBikeActivity.this).start();
            return;
        }

        //绑定车辆
        if (REQUEST_SIGN_BIND_BIKE_BY_CID == webSign && "".equals(webResult)) {
            Log.e(TAG, "dealDataFromWeb: ----------------------------- 绑定成功");
//            getUserBikes();
            //车辆数据已修改
            isChangeBike = true;

            //将历史存储车辆改成当前绑定车辆，便于回到主界面时展示该绑定车辆
            Map<String, String> spParams = new HashMap<>();
            spParams.put(SpConstant.HISTORY_CONNECT_BIKE_NAME_KEY, currentBindBikeName);
            HandleDataBySharePreferencesUtil.getInstance(this).putDateIntoSharePre(SpConstant.SP_NAME, spParams);

            //回退至主界面
            customBackEvent();
            return;
        }

        //获取二维码对应车辆信息
        if (REQUEST_SIGN_GET_BIKE_QRCODE == webSign) {
            if (webResult.contains("expired")) {
                //验证时间超时
                Toast.makeText(this, ToastConstant.QRCODE_VERIFICATION_TIMED_OUT, Toast.LENGTH_SHORT).show();
                return;
            } else if (webResult.contains("wrong auth")) {
                Toast.makeText(this, ToastConstant.QRCODE_WRONG_AUTH, Toast.LENGTH_SHORT).show();
                return;
            } else if (webResult.contains("none factory")) {
                Toast.makeText(this, ToastConstant.QRCODE_NONE_FACTORY, Toast.LENGTH_SHORT).show();
                return;
            } else if (webResult.contains("MissingParameter")) {
                Toast.makeText(this, ToastConstant.QRCODE_MISSING_PARAMETER, Toast.LENGTH_SHORT).show();
                return;
            }

            getInfoForBindBike(gson.fromJson(webResult, QrcodeResult.class).getQr_code());
            return;
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            } catch (Exception e) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
            return;
        }
    }

    /**
     * 处理页面跳转获取到的数据
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                //修改车辆昵称
                case REQUEST_CODE_CHANGE_BIKE_NICKNAME:

                    mBottomPopWindow.dismissing();

                    Bundle bundle = data.getExtras();
                    if (null == bundle || null == bundle.getString(ActivityChangeConstant.ACTIVITY_CHANGE_BIKE_NICKNAME_KEY)) {
                        Log.e(TAG, "onActivityResult: 自行车修改后的名称未找到");
                        return;
                    }
                    isChangeBike = true;
                    break;

                //获得 扫描二维码得到的车子 蓝牙特定名称和地址
                case REQUEST_CODE_FIND_BIKE_QRCODE:
                    Bundle qrCodeBundle = data.getExtras();

                    if (null == qrCodeBundle || null == qrCodeBundle.getString("result")) {
                        Log.e(TAG, "onActivityResult: 蓝牙设备地址和名称未取到");
                        return;
                    }
                    String result = qrCodeBundle.getString("result");
                    Log.i(TAG, "onActivityResult: 获取到的二维码信息 " + result);

                    //判断当前扫描的是Volta的二维码还是简版Volta的二维码
                    if (result.contains("volta:")) {
                        bike_name_prefix = "vta_";
                    } else if (result.contains("volta_b:")) {
                        bike_name_prefix = "vtb_";
                    }

                    if (result.contains("volta:")) {
                        //如果读取到的数据包含volta 则为向服务器获取二维码对应的数据
                        getInfoByQrcode(result.replace("volta:", "").replace("\n", "").replace("\r", ""));
                    } else {
                        //如果不包含，直接请求车辆数据
                        getInfoForBindBike(result);
                    }
                    break;
            }
        }

    }

    /**
     * 查询二维码对应的车辆信息
     */
    private void getInfoByQrcode(String info) {

        Integer index = new Random().nextInt(1010);
        //这里时间记住要用24小时制，否则会出错
        String time = DateFormatUtil.getStandardFormatTime().replace("Z", "");
        String auth = EncryptStringUtil.getMd5(new BigInteger(BluetoothDeviceConstant.AUTH_KEY_TAB[index], 16) + time + info + "X4cycleX4cycleX4cycleX4cycleX4cycle");

        Log.i(TAG, "getInfoByQrcode: info: " + info + " index " + index + " time: " + time + " auth " + auth);

        Map<String, String> map = new HashMap<>();
        map.put(WebConstant.GET_BIKE_QRCODE_INFO, info);
        map.put(WebConstant.GET_BIKE_QRCODE_ID, index + "");
        map.put(WebConstant.GET_BIKE_QRCODE_TIME, time);
        map.put(WebConstant.GET_BIKE_QRCODE_AUTH, auth);
        new GetJsonFromWebJob(WebConstant.GET_BIKE_QRCODE_PATH, WebConstant.GET, map, REQUEST_SIGN_GET_BIKE_QRCODE, MyBikeActivity.this).start();
    }

    /**
     * 利用获得的车辆信息查询数据 为将其绑定到用户名下做准备
     *
     * @param result
     */
    private void getInfoForBindBike(String result) {
        //蓝牙设备信息
        String bikeName = (bike_name_prefix + getBluetoothKeyId(result)).replace("\n", "").replace("\r", "").replace("+", "%2B").replace("/", "%2F");

        Log.i(TAG, "getInfoForBindBike: 获取车辆名称--" + bikeName);

        //获取当前扫描二维码得到的车辆名称获取对应车辆信息
        Map<String, String> map = new HashMap<>();
        map.put(WebConstant.FIND_BIKE_BY_NAME_NAME, bikeName);
        new GetJsonFromWebJob(WebConstant.FIND_BIKE_BY_NAME_PATH, WebConstant.POST, map, REQUEST_SIGN_GET_BIKE_BID_BY_BNAME_BIND_USER, MyBikeActivity.this).start();

    }

    /**
     * base64反编译解析出车辆mac地址
     *
     * @param code
     * @return
     */
    private String getBluetoothKeyId(String code) {
        String[] params = code.split(" ");
        Log.i(TAG, "getBluetoothKeyId: " + params.length);
        if (params.length < 3) {
            return null;
        }

        Integer index = Integer.parseInt(params[1]);
        String key = EncryptStringUtil.getMd5(BluetoothDeviceConstant.AUTH_KEY_TAB[index].toUpperCase() + " " + params[2] + " " + "X4cycleX4cycleX4cycleX4cycleX4cycle").substring(0, 16).toUpperCase();
        String value = params[0];

        BigInteger bigInteger1 = new BigInteger(value, 16);
        BigInteger bigInteger2 = new BigInteger(key, 16);

        String str1 = bigInteger1.xor(bigInteger2).toString(16);

        StringBuilder sbId = new StringBuilder();
        for (int i = 0; i < str1.length(); i = i + 2) {
            String s = str1.substring(i, i + 2);
            byte byte1 = (byte) Integer.parseInt(s, 16);
            sbId.append((char) byte1);
        }
        return sbId.toString();
    }

    /***********************************************************************************************/
    /**                                       自定义BaseAdapter方法                                **/
    /***********************************************************************************************/

    /**
     * 自定义缓存复用类
     */
    class ViewHolder {
        TextView tv_detail_bike_name;
        TextView tv_detail_bike_location;
        TextView tv_detail_bike_time;

        RelativeLayout rl_bike_name_info;
        RelativeLayout rl_bike_location_info;
        RelativeLayout rl_bike_time_info;
    }

    /**
     * 自定义BaseAdapter
     */
    class MyBikeDetailAdapter extends BaseAdapter {

        private MyBikeActivity.ViewHolder viewHolder;

        @Override
        public int getCount() {
            return bikeDetailList.size();
        }

        @Override
        public Object getItem(int position) {
            return bikeDetailList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return bikeDetailList.get(position).hashCode();
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = LayoutInflater.from(MyBikeActivity.this);

            final BikeInfoResult bikeInfoResult = bikeDetailList.get(position);

            if (null == convertView) {
                convertView = inflater.inflate(R.layout.fragment_bike_info, null);
                viewHolder = new MyBikeActivity.ViewHolder();
                viewHolder.tv_detail_bike_name = (TextView) convertView.findViewById(R.id.tv_detail_bike_name);
                viewHolder.tv_detail_bike_location = (TextView) convertView.findViewById(R.id.tv_detail_bike_location);
                viewHolder.tv_detail_bike_time = (TextView) convertView.findViewById(R.id.tv_detail_bike_time);

                viewHolder.rl_bike_name_info = (RelativeLayout) convertView.findViewById(R.id.rl_bike_name_info);
                viewHolder.rl_bike_location_info = (RelativeLayout) convertView.findViewById(R.id.rl_bike_location_info);
                viewHolder.rl_bike_time_info = (RelativeLayout) convertView.findViewById(R.id.rl_bike_time_info);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (MyBikeActivity.ViewHolder) convertView.getTag();
            }

            String bikeName = bikeInfoResult.getName();
            String bikeNickname = bikeInfoResult.getNickname();
            String location = "(" + (null == bikeInfoResult.getLat() ? "---" : bikeInfoResult.getLat()) + "," + (null == bikeInfoResult.getLng() ? "---" : bikeInfoResult.getLng()) + ")";
            String locationTime = bikeInfoResult.getUpdated_at().replace("T", " ").replace("Z", "");

            //设置车的名称
            viewHolder.tv_detail_bike_name.setText(null == bikeNickname || "".equals(bikeNickname) ? bikeName : bikeNickname);
            viewHolder.tv_detail_bike_location.setText(location);
            viewHolder.tv_detail_bike_time.setText(locationTime);

            viewHolder.rl_bike_name_info.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    //展示自行车 解绑 改名等部分操作的popWindow
                    mBottomPopWindow.showing();

                    //得到当前所选的自行车ID
                    currentBike = bikeInfoResult;
                }
            });

            return convertView;
        }
    }
}
